<template>
<div>
    <el-card style="padding:10px;background:#EBEEF5">
    <div style="margin: 10px 0;width: 100%">
      <el-button type="primary" :icon="CirclePlus" v-if="user.role=='主持人'" @click="add">新增</el-button>
      <el-upload   :action="'http://localhost:9090/game/import'"   :on-success="handleUploadSuccess"   :show-file-list=false     accept="xlsx"   style="display: inline-block; margin: 0 10px" >
        <el-button v-if="user.role=='主持人'" type="primary" :icon="Download">导入</el-button>
      </el-upload>
      <el-button v-if="user.role=='主持人'" :icon="Upload"  type="primary" @click="exportUser">导出</el-button>

      <el-input v-model="gamename" placeholder="请输入比赛名" style="width: 15%;margin: 0 10px 0 50px" clearable/>
      <el-button type="primary" :icon="Search" style="margin-left: 10px" @click="load">查询</el-button>
      <el-button type="primary" :icon="Refresh" style="margin-left: 10px" @click="reset">重置</el-button>
    </div>
      <div style="width:100%;  " v-for="(item,index) in tableData" :key="item.id">
        <el-card :body-style="{ margin:'10px 10px',background: '#FFFFFF',display: 'flex' }">
          <div style="height: 100%;width:150px ">
            <el-image style="width: 100px; height: 100px" :src="item.cover" fit="fill" />
          </div>
          <div style="margin: 0 10px;width: 900px">
            <h1>比赛名称:{{item.gameName}}</h1>
            <p>主持人:<strong>{{item.master}}</strong></p>
            <p>裁判:<strong v-for="(judge,index) in Judges">{{judge.nickName + " "}} </strong></p>
            <p>简介:{{item.description}}</p>
          </div>
          <div  >
            <el-container style="height: 50%" slot-scope="scope">
              <el-button type="primary" :icon="Edit" v-if="user.role=='主持人'||user.role=='管理员'" @click="handleEdit(item)">编辑
              </el-button>
              <el-button type="primary" :icon="Edit" v-if="user.role=='主持人'||user.role=='管理员'" @click="judgesAllot(item)">分配裁判
              </el-button>
              <el-popconfirm title="确定要删除吗?" @confirm="handleDelete(item.id)">
                <template #reference>
                  <el-button :icon="Remove" v-if="user.role=='主持人' ||user.role=='管理员'" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
              <el-button type="primary" :icon="Edit" v-if="user.role=='裁判员' || user.role=='管理员' "   @click="grade(item)">评阅成绩
              </el-button>
            </el-container>
            <el-container style="height: 50%">

              <el-button type="primary" :icon="Edit" v-if="user.role=='主持人'||user.role=='管理员'"   @click="selectRule(item)">设置规则
              </el-button>
              <el-upload     :action="'http://localhost:9090/item/import'"   :on-success="handleUploadSuccess"   :show-file-list=false     accept="xlsx"   style="display: inline-block; margin: 0 10px" >
                <el-button type="primary" v-if="user.role=='主持人'||user.role=='管理员'" :icon="Download">导入作品</el-button>
              </el-upload>
              <el-button type="primary" :icon="Edit" v-if="user.role=='主持人'||user.role=='管理员'" @click="viewScores(item)" >查看成绩
              </el-button>
              <el-button type="primary" :icon="Edit" v-if="user.role=='主持人'||user.role=='管理员'" @click="viewItem(item)">查看作品
              </el-button>
            </el-container>
          </div>
        </el-card>
      </div>
    <div style="margin: 10px 0">
      <el-dialog
          v-model="dialogVisible"
          title="提示"
          width="30%"
      >
        <el-form label-width="120px">
          <el-form-item :model="form" label="比赛名">
            <el-input v-model="form.gameName" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item :model="form" label="创建时间">
            <el-date-picker v-model="form.createTime" value-format="YYYY-MM-DD" type="datetime" style="width: 80%" clearable></el-date-picker>
          </el-form-item>
          <el-form-item :model="form" label="截止时间">
            <el-date-picker v-model="form.endTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetime" style="width: 80%" clearable></el-date-picker>
          </el-form-item>
          <el-form-item :model="form" label="主持人">
            <el-input v-model="form.master" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item :model="form" label="封面">
            <el-upload
                action="http://localhost:9090/file/upload"
                :on-success="filesUploadSucesss"
                ref="upload"
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item :model="form" label="简介">
            <el-input type="textarea" v-model="form.description" style="width: 80%"></el-input>
          </el-form-item>

        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary"  @click="save">确定</el-button>
      </span>
        </template>
      </el-dialog>

      <el-dialog
          v-model="dialogJudgeVisible"
          title="提示"
          width="30%"
      >
        <el-form label-width="120px">
          <el-form-item :model="judgeForm" label="裁判">
            <el-select clearable v-model="judgeForm" placeholder="请选择">
              <el-option v-for="item in Judges" :key="item.id" :label="item.nickName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogJudgeVisible = false">取消</el-button>
        <el-button type="primary"  @click="saveJudge">确定</el-button>
      </span>
        </template>
      </el-dialog>

      <el-dialog
          v-model="dialogRulesVisible"
          title="提示"
          width="80%"
      >

        <div  v-for="(item, index) in rulesData" :key="index" class="inlineForm">
          <el-form style="display: flex;align-items: center;"  label-width="100px" >
            <el-form-item
                :model="item"
                label="id"
            >
              <el-input v-model="item.id"></el-input>
            </el-form-item>
            <el-form-item
                :model="item"
                label="规则描述"
            >
              <el-input type="textarea" v-model="item.message"></el-input>
            </el-form-item>
            <el-form-item
                :model="item"
                label="占比(%)"
            >
              <el-input v-model="item.percent"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="addDomain">增加</el-button>
              <el-button v-if="rulesData.length > 1" type="danger"  circle @click.prevent="removeDomain(item)">删除</el-button>
            </el-form-item>
          </el-form>
        </div>
<!--        <span slot="footer" style="margin-left: 200px">-->
<!--        <el-button type="primary" @click="submitRulesData()">提交</el-button>-->
<!--      </span>-->
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogRulesVisible = false">取消</el-button>
        <el-button type="primary"  @click="saveRule">确定</el-button>
      </span>
        </template>
      </el-dialog>
      <el-dialog
          v-model="dialogRulesDataVisible"
          title="提示"
          width="80%"
      >


      </el-dialog>

      <el-dialog
          v-model="dialogViewScores"
          title="提示"
          width="80%"
      >
        <el-card style="padding:10px;background:#EBEEF5">
          <div style="margin: 10px 0;width: 100%">
            <el-button :icon="Upload"  type="primary" @click="exportScore">导出</el-button>
          </div>
          <el-table :data="viewScoresData"  :row-style="tableRowStyle" :cell-style="{'text-align':'center'}" :header-cell-style="{'text-align':'center'}"
                    border resizable="true" style="width: 100%" >
            <!--      <el-table-column prop="id" label="ID" sortable/>-->
            <el-table-column prop="gameName" label="比赛名称"/>
            <el-table-column prop="nickName" label="学生/团队名称"/>
            <el-table-column prop="title" label="作品名称"/>
            <el-table-column prop="allScore" label="总分" sortable/>

          </el-table>
        </el-card>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogViewScores = false">确定</el-button>
      </span>
        </template>
      </el-dialog>


      <el-dialog
          v-model="dialogViewItems"
          title="提示"
          width="80%"
      >
        <el-card style="margin:10px 10px;padding:10px;background:#EBEEF5">
          <el-table :data="viewItemData"  :row-style="tableRowStyle" :cell-style="{'text-align':'center'}" :header-cell-style="{'text-align':'center'}"
                    border resizable="true" style="width: 100%">
            <el-table-column prop="id" label="ID" sortable/>
            <el-table-column prop="userId" label="学生id"/>
            <el-table-column prop="title" label="作品名称"/>
          </el-table>
        </el-card>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogViewItems = false">确定</el-button>
      </span>
        </template>
      </el-dialog>
    </div>
  </el-card>
  <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[2,5,10,20]"
      :page-size="pageSize"
      layout="total,sizes,prev,pager,next,jumper"
      :total="total">
  </el-pagination>
</div>
</template>
<script>
import request from "@/utils/request";
import {getGameList} from "@/api/api";
import { Edit,Remove,CirclePlus,Upload,Download,Search,Refresh,View,CircleClose } from '@element-plus/icons-vue';
import {ElMessage} from "element-plus";
export default {
  setup(){
    return{
      Edit,
      Remove,
      CirclePlus,
      Upload,
      Download,
      Search,
      Refresh,
      View,
      CircleClose
    }
  },
  name: 'Game',
  components: {Edit},
  data() {
    return {
      form: {},
      judgeForm: 0,
      dialogVisible: false,
      dialogJudgeVisible: false,
      dialogRulesVisible:false,
      dialogViewScores:false,
      dialogViewItems:false,
      dialogRulesDataVisible:false,
      currentPage: 1,
      total: 0,
      pageSize: 5,
      gamename:"",
      tableData: [],
      isShow:false,
      ids:0,
      roles:[],
      rulesForm:{
        gameId:-1,
        ruleId:-1
      },
      Judges:[],
      gameId:null,
      user:{},
      judge:[],
      rules:[],
      viewScoresData:[],
      viewItemData:[],
      id:null,
      newRulesData:[],
      rulesData:[
          {
            id:"",
            message:"",
            percent:""
          },
        ],

    }
  },
  created() {
    this.load();

  },
  methods: {
    submitRulesData(){
      this.$store.commit('setRulesData', this.rulesData)
      // this.$store.state.menus.menuList
      console.log(this.$store.state.rulesData)
    },

    addDomain() {
      this.rulesData.push(          {
        id:"",
        message:"",
        percent:""
      })
    },
    removeDomain(item) {
      const index = this.rulesData.indexOf(item)
      if (index !== -1) {
        this.rulesData.splice(index, 1)
      }
    },
    viewItem(item){
      let id= item.id
      request.get("/item/"+id).then(res=>{
        // console.log(res)
        if (res.data.length>0){
          this.viewItemData=res.data
        }
      })
      this.dialogViewItems=true
    },
    viewScores(item){
      this.id = item.id
      // console.log(id)
      request.get("/score/allScore/"+this.id).then(res =>{
        // console.log(res)
        this.viewScoresData=res.data
      })
      this.dialogViewScores=true
    },
    exportScore() {
      location.href = "http://localhost:9090/score/export/"+this.id;
    },
    async selectRule(row){
        this.gameId=row.id
        await request.get("/game/rules/"+this.gameId).then(res =>{
          // console.log(res)
          this.rulesData=res.data
        })
        this.rulesForm.ruleId = row.rule

      this.dialogRulesVisible=true
    },
    grade(item){
      // console.log(item)
      let routerJump=this.$router.resolve({
        path:'/correct',
        query:{
          gameId:item.idx
        }
      })
      sessionStorage.setItem('gameId',JSON.stringify(item.id))
      window.open(routerJump.href,'_blank')
    },
    tableRowStyle({ row, rowIndex }) {
      return { background:'#F2F6FC', color: '#0052d9', 'font-weight': 600 }
    },
    reset(){
      this.gamename="";
      this.load()
    },
    Show(){
      this.isShow=!this.isShow
    },
    deleteBatch(){
      if(!this.ids.length){
        this.$message.warning("请选择数据!")
        return
      }
      request.post("/game/del/batch",this.ids).then(res=>{
        if(res){
          this.$message.success("批量删除成功")
          this.load()
        }else{
          this.$message.error("批量删除失败")
        }
      })
    },
    handleSelectionChange(val){
      this.ids=val.map(v => v.id)
    },
    handleUploadSuccess(res) {
      if (res.code === 200) {
        this.$message.success("导入成功")
        this.load()
      }
    },
    exportUser() {
      location.href = "http://localhost:9090/game/export";
    },

    showBooks(books){
      this.bookList=books;
      this.bookVis=true
    },

    load() {
      this.user= JSON.parse(localStorage.getItem("user"))
      // console.log(this.user.role)
      const params= {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        gamename: this.gamename,
      }
      getGameList(params).then(res => {
        // console.log(res)
        this.tableData = res.data.records;
        this.total = res.total
      })

      request.get("/game/judge").then(res =>{
        // console.log(res)
       if (res.code === 200){
         this.Judges=res.data
         // console.log(this.Judges)
       }else{
         ElMessage({
           message: '获取裁判列表失败',
           type: 'error',
         })
       }
      })

      request.get("/game/rules").then(res =>{
        // console.log(res)
        if (res.code === 200){
          this.rules=res.data

        }else{
          ElMessage({
            message: '获取规则列表失败',
            type: 'error',
          })
        }
      })

    },
    add() {
      this.dialogVisible = true;
      this.form = {}
      this.$refs["upload"].clearFiles()
    },
    judgesAllot(item){
      this.gameId=item.id
      // console.log(this.gameId)
      this.judgeForm = JSON.stringify(item.judges);
      // console.log(...item.judges)
      this.dialogJudgeVisible = true
    },

    saveRule(){


      request.post("/rules/add/"+this.gameId, this.rulesData).then(res => {

        if (res.code === 200) {
          ElMessage({
            type: "success",
            message: "设置规则成功"
          })
        } else {
          ElMessage({
            type: "error",
            message: "设置规则失败"
          })
        }
        this.dialogRulesVisible = false
        this.load();
      })
    },
    saveJudge(){
      request.post("/game/add", this.gameId).then(res => {
        if (res.code === 200) {
          ElMessage({
            type: "success",
            message: "裁判员分配成功"
          })
        } else {
          ElMessage({
            type: "error",
            message: "裁判员分配失败"
          })
        }
        this.load();
        this.dialogJudgeVisible = false
      })

      this.ids = this.judgeForm;
      //console.log("ids = " + this.ids);

      request.post("/game/addJudge/" + this.gameId, this.ids).then(res => {
        if (res.code === 200) {
          ElMessage({
            type: "success",
            message: "数据更新成功"
          })
        } else {
          ElMessage({
            type: "error",
            message: "数据更新失败"
          })
        }
      })

      this.ids=[]
    },
    save() {
      if (this.form.id) {
        request.post("/game/add", this.form).then(res => {
          // console.log(res);
          if (res.code === 200) {
            ElMessage({
              message: '更新成功',
              type: 'success',
            })
          } else {
            ElMessage({
              message: '更新失败',
              type: 'error',
            })
          }
          this.load();
          this.dialogVisible = false
        });
      } else {
        request.post("/game/add", this.form).then(res => {
          // console.log(res);
          if (res.code === 200) {
            ElMessage({
              type: "success",
              message: "新增成功"
            })
          } else {
            ElMessage({
              type: "error",
              message: "新增失败"
            })
          }
          this.load();
          this.dialogVisible = false
        })
      }
    },
     handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row));
      this.dialogVisible = true
      this.$refs["upload"].clearFiles()
    },
    handleSizeChange(pageSize) {
      this.pageSize=pageSize;
      this.load();
    },
    handleCurrentChange(pageNum) {
      this.currentPage=pageNum;
      this.load();
    },
    filesUploadSucesss(res){
      this.form.cover=res
    },
    handleDelete(id){
      // console.log(id)
      request.delete("/game/"+id).then(res => {
        // console.log(res.code)
        if (res){
          ElMessage({
            type: "success",
            message: "删除成功"
          })
        }else {
          this.$message({
            type: "error",
            message: "删除失败"
          })
        }
        this.load()//重新加载
      });
    }
  }
}
</script>


<style>
p{
  margin: 5px;
}
</style>